<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <meta name="description" content="遇见与成长 - 图腾客户管理系统 - 用户列表">
    <title>{{title}}</title>
    <link rel="stylesheet" href="/apps/css/bootstrap.min.css">
    <link rel="stylesheet" href="/apps/css/fontawesome-free-6.4.0-web/css/all.css">
    <link rel="stylesheet" href="/apps/css/mui.css">
</head>
<body>
    <header class="d-flex align-items-center bg-custom-color p-3">
        <button id="backButton" class="btn btn-primary rounded-circle me-3" style="background-color: white;" onclick="history.back();">
            <i class="fas fa-arrow-left custom-color"></i>
        </button>
        <span class="title-text text-white fs-5">{{excerpt}}</span>
    </header>
    <div class="container">
        <div class="content">
            <div class="row">
                <div class="col-12">
                    <p>{{{description}}}</p>
                    <div class="table-responsive">
                        <table class="table table-striped table-bordered">
                            <thead class="table-light">
                                <tr>
                                    <th scope="col" class="cell-content">id|code</th>
                                    <th scope="col" class="cell-content">task</th>
                                    <th scope="col" class="cell-content">status</th>
                                </tr>
                            </thead>
                            <tbody>
                                {{#each rows}}
                                <tr data-id="{{this.id}}" onclick="showDataModal('{{this.id}}','{{this.status}}', '{{this.entry}}', '{{this.result}}');">
                                    <td class="cell-content" width="15%;">
                                        <!-- Display UID and circular image -->
                                        <small>#{{this.id}} P{{this.publisher_uid}}A{{this.assignee_uid}}</small><br>
                                        <small>{{this.code}}</small><br>
                                    </td>
                                    <td class="cell-content">
                                        <small>{{{this.description}}}</small><br>
                                        <small>{{{this.title}}}</small><br>
                                        <small style="color:#c1c1c1">{{{this.created_at}}}</small>
                                    </td>
                                    <td class="cell-content">
                                        <small>{{{this.taskInfo}}}</small><br>
                                        <small style="color:#c1c1c1">{{{this.updated_at}}}</small>
                                    </td>
                                </tr>
                                {{/each}}
                            </tbody>
                        </table>
                </div>
            </div>
        </div>
    </div>

    <nav aria-label="Page navigation" class="pagination-container">
        <button id="homeButton" class="btn btn-primary position-absolute top-0 start-0 m-3 rounded-circle" style="width: 50px; height: 50px; padding: 0;" onclick="window.location.href='https://totemlife.cn/apps/crm/';">
            <i class="fas fa-home" style="color:white;"></i>
        </button>
        <button id="formButton" class="btn btn-primary position-absolute top-0 end-0 m-3 rounded-circle" style="width: 50px; height: 50px; padding: 0;" onclick="showQueryForm();">
            <i class="fas fa-search" style="color: white;"></i>
        </button>
        <ul class="pagination">
            {{{paginator}}}
        </ul>
    </nav>

</div>

<div class="modal fade" id="clientModal" tabindex="-1" aria-labelledby="clientModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="clientModalTitle">选择数据操作</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body" id="clientModalBody" style="text-align:center;">
            </div>
            <div class="modal-footer" id="clientModalFooter">
                <button type="button" class="btn btn-primary" data-bs-dismiss="modal">关闭操作窗口</button>
            </div>
        </div>
    </div>
</div>

<div class="modal fade" id="queryModal" tabindex="-1" aria-labelledby="queryModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="queryModalLabel">设置统计参数</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <form id="queryForm" onsubmit="submitQueryForm()">
                <div class="modal-body">
                    <div class="row">
                        <div class="col">
                            <div class="mb-2">
                                <label for="begin" class="form-label">创建日期起始</label>
                                <input type="date" class="form-control" id="begin" name="begin" value="{{begin}}">
                            </div>
                        </div>
                        <div class="col">
                            <div class="mb-2">
                                <label for="end" class="form-label">创建日期截至</label>
                                <input type="date" class="form-control" id="end" name="end" value="{{end}}">
                            </div>
                        </div>
                    </div>
                    <div class="row">
                        <div class="col">
                            <div class="mb-2">
                                <label for="publisherUid" class="form-label">发布者UID</label>
                                <input type="text" class="form-control" id="publisherUid" name="publisherUid" value="{{publisherUid}}" placeholder="publisherUid">
                            </div>
                        </div>
                        <div class="col">
                            <div class="mb-2">
                                <label for="assigneeUid" class="form-label">接受者UID</label>
                                <input type="text" class="form-control" id="assigneeUid" name="assigneeUid" value="{{assigneeUid}}" placeholder="assigneeUid">
                            </div>
                        </div>
                        <div class="col">
                            <div class="mb-2">
                                <label for="status" class="form-label">任务代码</label>
                                <select class="form-select" id="status" name="status">
                                    <option value="">全部状态</option>
                                    <option value="pending">待处理</option>
                                    <option value="inProgress">进行中</option>
                                    <option value="cancelled">已取消</option>
                                    <option value="finished">已完成</option>
                                    <option value="onHold">暂停中</option>
                                </select>
                            </div>
                        </div>
                    </div>
                    <div class="row">
                        <div class="col">
                            <div class="mb-6">
                                <label for="code" class="form-label">任务代码</label>
                                <select class="form-select" id="code" name="code">
                                    <option value="">所有任务代码</option>
                                    <option value="crep-follow-tmall-registration">代表跟进-商城新访客</option>
                                    <option value="crep-follow-mta-registration">代表跟进-MTA新访客</option>
                                    <option value="crep-follow-npo-order">代表跟进-首单新用户</option>
                                </select>
                            </div>
                        </div>
                        <div class="col-6">
                            <div class="mb-2">
                                <label for="tinfo" class="form-label">任务信息</label>
                                <input type="text" class="form-control" id="tinfo" name="tinfo" value="{{tinfo}}" placeholder="可搜任务相关信息">
                            </div>
                        </div>
                    </div>
                </div>
                <div class="modal-footer" id="clientModalFooter">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">关闭查询</button>
                        <button type="submit" class="btn btn-primary">查询数据</button>
                </div>
            </form>
        </div>
    </div>
</div>

<div class="modal fade" id="inputModal" tabindex="-1" aria-labelledby="inputModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="inputModalLabel">请输入取消任务的原因</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <input type="text" class="form-control" id="cancelReason" placeholder="请输入取消任务的原因">
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-primary" onclick="submitCancelReason()">确认</button>
            </div>
        </div>
    </div>
</div>

<footer class="footer" style="text-align: center;">
    <div class="row">
        <div class="text-muted">&nbsp;</div>
        <div class="text-muted">&nbsp;</div>
        <div class="text-muted">&copy;2023 图腾生命医学</div>
        <div class="text-muted">我们为人类免疫事业而奉献</div>
    </div>
</footer>

<script src="https://res.wx.qq.com/open/js/jweixin-1.6.0.js"></script>
<script src="/apps/js/bootstrap.bundle.min.js"></script>
<script src="/apps/js/crm-hbs-utils.js"></script>
<script src="/apps/js/wx-client-dom.js"></script>
<script>
    const totemUID = parseInt("{{totemUID}}") || 0;
    function showQueryForm() {
        const modal = new bootstrap.Modal(document.getElementById('queryModal'));
        modal.show();
    };
    function showDataModal(id, status, entry, result) {
        const selectedDataId = id;
        const modal = new bootstrap.Modal(document.getElementById('clientModal'));
        const modalTitle = document.getElementById('clientModalTitle');
        modalTitle.textContent = `任务T#${selectedDataId}的操作`;
        const modalBody = document.getElementById('clientModalBody');

        let doTask = '';
        if(status=='pending') doTask = `<a style="text-decoration: none;" href="${entry}"><h5>去执行任务</h5></a><hr>`;
        if(status=='finished' || status == 'completed') doTask = `<h5 style="color:#c1c1c1;">任务已完成</h5><hr>`;

        let viewResult = '';
        if(status=='finished' || status == 'completed' ) viewResult = `<a style="text-decoration: none;" href="${result}"><h5>看任务成果</h5></a><hr>`;
        if(status=='pending') viewResult = `<h5 style="color:#c1c1c1;">无任务成果</h5><hr>`;

        let cancelTask = '';
        if( status != 'finished' && status!= 'completed' && status != 'cancelled' )
            //cancelTask = `<h5 onclick="cancelTaskModal(${id})">中止此任务</h5>`;
            //cancelTask = `<a style="text-decoration: none;" href=""><h5>中止此任务</h5></a>`;
            cancelTask = `<a style="text-decoration: none;" href=""><h5 onclick="cancelTaskModal(${id})">中止此任务</h5></a>`;
        if(status=='cancelled') cancelTask = `<h5 style="color:#c1c1c1;">任务已中止</h5>`;
        if(status=='finished' || status == 'completed') cancelTask = `<h5 style="color:#c1c1c1;">任务已完成</h5>`;

        modalBody.innerHTML = `${doTask} ${viewResult} ${cancelTask}`;
        modal.show();
    };
    function submitQueryForm() {
        const queryParams = new URLSearchParams();
        const paramsToCheck = ['begin', 'end', askerUid, id, publisherUid, assigneeUid, code, status, tinfo, cinfo ];
        for (const param of paramsToCheck) {
            const value = encodeURIComponent(document.getElementById(param).value);
            if (value && value !== '') queryParams.append(param, value);
        }
        const url = `https://totemlife.cn/apps/crm/users?${queryParams.toString()}`;
        window.location.href = url;
    }
    function cancelTaskModal(id) {
		alert('中止功能即将上线，请稍后再试！');
		return;
        const reason = prompt(`请输入中止任务#${id}的原因：`);
        if (reason !== null) {
            cancelTask(id, reason);
        }
    }
    function cancelTaskModalNew(id) {
        const modal = new bootstrap.Modal(document.getElementById('inputModal'));
        modal.show();
        // 将任务 ID 存储在模态框的数据属性中，以便后续使用
        modal.relatedTarget = id;
    }
    function submitCancelReason() {
        const reason = document.getElementById('cancelReason').value;
        const id = document.querySelector('.modal.show').relatedTarget;
        cancelTask(id, reason);
        // 关闭模态框
        document.getElementById('inputModal').hide();
    }
    function cancelTask(id, reason) {
        // 发送任务中止请求到后端
        fetch(`/apps/crm/cancel-task/${id}`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({ reason: reason }),
        })
        .then(response => {
            if (response.ok) {
                // 中止成功，修改任务状态提示
                const row = document.querySelector(`tr[data-id="${id}"]`);
                row.querySelector('.cell-content').innerHTML = `<h5 style="color:#c1c1c1;">任务已中止</h5>`;
            } else {
                throw new Error('中止任务失败');
            }
        })
        .catch(error => {
            alert(error.message);
        });
    }
    </script>
</body>
</html>
